#include <iostream>

#include "CLock.h"

using namespace std;

int main(int argc, char* argv[])
{
	if(argc<2) {
		printf("usages: %s <file to lock>\n", argv[0]);
		return -1;
	}

cout << "########################################################################" << endl;
cout << "p1 won't unlock after lock in 9th count" << endl;
cout << "nevertheless, p2 will lock it which is in unlock by p1 without blocking" << endl;
cout << "########################################################################" << endl;
cout << endl;

	pid_t pid = fork();
	if(pid!=0) {
		printf("p1 is started\n");

		for(int i=0;i<10;i++) {
			CLock lock;

cout << "#p1[" << i << "] lock" << endl;
			if(lock.lock()!=0) printf("[p1]lock failure\n");
			else {
				ofstream xxx(argv[1], ios::app|ios::out);
				xxx << "p1[" << i << "]" << endl;
			}

if(i==9) {
	cout << "##################### here #######################" << endl;
	cout << "#p1 will be dead without unlock" << endl;
	cout << "##################################################" << endl;
	break;
}

cout << "#p1[" << i << "] unlock" << endl;
			if(lock.unlock()!=0) printf("[p1]lock failure\n");
		}

		printf("p1 is finished\n");

		exit(0);
	}
	else {
		printf("p2 is started\n");

		for(int i=0;i<10;i++) {
			CLock lock;

cout << "#p2[" << i << "] lock" << endl;
			if(lock.lock()!=0) printf("[p2]lock failure\n");
			else {
				ofstream xxx(argv[1], ios::app|ios::out);
				xxx << "p2[" << i << "]" << endl;
			}

cout << "#p2[" << i << "] unlock" << endl;
			if(lock.unlock()!=0) printf("[p2]lock failure\n");
		}

		printf("p2 is finished\n");

		return 0;
	}
}
